/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.myhouse.conf;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

//从Spring3.0，@Configuration用于定义配置类，可替换xml配置文件，被注解的类内部包含有一个或多个被@Bean注解的方法，这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描，并用于构建bean定义，初始化Spring容器。
//@Configuration标注在类上，相当于把该类作为spring的xml配置文件中的<beans>，作用为：配置spring容器(应用上下文)
/**
@Configuation总结
 1). @Configuation等价于<Beans></Beans>
 2). @Bean等价于<Bean></Bean>
 3). @ComponentScan等价于<context:component-scan base-package="com.dxz.demo"/>
 */
@Configuration

//WebMvcConfigurerAdapter是Spring内部的一种配置方式
//采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制
//在SpringBoot2.0及Spring 5.0 WebMvcConfigurerAdapter已被废弃，目前找到解决方案就有两种
//1 直接实现WebMvcConfigurer （官方推荐）
//2 直接继承WebMvcConfigurationSupport
//public class WebMvcConfig extends WebMvcConfigurerAdapter {
public class WebMvcConfig implements WebMvcConfigurer {

	/** 静态资源处理 **/
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
    
    /** 解决跨域问题 **/
    public void addCorsMappings(CorsRegistry registry) {
	}

    /** 添加拦截器 **/
    public void addInterceptors(InterceptorRegistry registry) {
    	//拦截器测试
    	registry.addInterceptor(new ReqInterceptor()).addPathPatterns("/**");
    	
    	//增加统一日志打印
    	registry.addInterceptor(new LoggerInterceptor()).addPathPatterns("/**").excludePathPatterns("/static/**");
	}

    /** 这里配置视图解析器 **/
    public void configureViewResolvers(ViewControllerRegistry registry) {
    	System.out.println("configureViewResolvers...");
    	registry.addViewController("/").setViewName("/index");
    	//实现一个请求到视图的映射，而无需书写controller
        //registry.addViewController("/login").setViewName("forward:/index.html");  
	}

    /** 配置内容裁决的一些选项 **/
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
	}

    /** 视图跳转控制器 **/
    public void addViewControllers(ViewControllerRegistry registry) {
	}

    /** 默认静态资源处理器 **/
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
	}
    
    /**
     * Http序列化和反序列化的核心是HttpMessageConverter, 在springmvc和springboot中，均默认采用MappingJackson2HttpMessageConverter来实现JSON数据的处理
     * 消息转换器的目标是：HTTP输入请求格式向Java对象的转换；Java对象向HTTP输出请求的转换。
     * 修改自定义消息转换器
     * @param converters 消息转换器列表
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    	//创建fastJson消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //创建配置类
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //修改配置返回内容的过滤
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //将fastjson添加到视图消息转换器列表内
        converters.add(fastConverter);
        
    }
}
